<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="form-box">
          <BasicForm @register="registerForm" />
          <div class="btns">
            <a-button class="btns-one" @click="handleResetFields" v-if="hasPermission('11-1-reset')"
              >重置</a-button
            >
            <a-button type="primary" @click="throttleSubmit" v-if="hasPermission('11-1-save')"
              >提交</a-button
            >
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getFormErrorMessage } from '/@/utils/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDatabaseType, setHDAConfig, getHDAConfig } from '/@/api/hda/index';
  import { listModel } from './type';
  let dataBaseTypeList: listModel[] = [];
  const { hasPermission } = usePermission();
  // 是否第一次打开页面
  let isCreate = true;
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'divider-basic',
      component: 'Divider',
      label: '数据库配置',
      colProps: {
        span: 24,
      },
      componentProps: {
        orientationMargin: '10px',
      },
    },
    {
      field: 'DBType',
      component: 'Select',
      label: '数据库类型：',
      colProps: {
        span: 14,
      },
      componentProps: {
        options: [],
        onChange: (e) => {
          let tagretInfo = dataBaseTypeList.filter((item) => item.value === e);
          if (tagretInfo.length > 0 && !isCreate && e) {
            setFieldsValue({ ConnectString: tagretInfo[0].name });
          } else {
            isCreate = false;
          }
        },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择数据库类型');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ConnectString',
      component: 'Input',
      label: '连接字符串：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入连接字符串',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ExpriedTime',
      component: 'InputNumber',
      label: '过期时间：',
      colProps: {
        span: 14,
      },
      componentProps: {},
      rules: [
        {
          required: true,
          message: '请输入过期时间',
          trigger: ['change', 'blur'],
        },
      ],
      suffix: '(小时)',
    },
  ];

  let loading = ref<boolean>(false);
  let oldValue = {};
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  onMounted(async () => {
    getTypeList();

    try {
      let resByConfig = await getHDAConfig();

      let setValue = {
        ConnectString: resByConfig.ConnectString,
        DBType: resByConfig.DBType,
        ExpriedTime: resByConfig.ExpriedTime,
      };
      oldValue = setValue;
      setFieldsValue(setValue);
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  });
  const throttleSubmit = useDebounceFn(handleSubmint, 500);
  async function getTypeList() {
    loading.value = true;
    try {
      let res = await getDatabaseType();
      let list: listModel[] = res.map((item) => {
        return { label: item.Key, value: item.Value, name: item.Name };
      });
      dataBaseTypeList = list;
      updateSchema({ field: 'DBType', componentProps: { options: list } });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  async function handleSubmint() {
    loading.value = true;

    try {
      let res = await validateFields();
      loading.value = false;
      await setHDAConfig([res]);
      loading.value = false;
      createMessage.success(t('layout.setting.operatingTitle'));
    } catch (error: any) {
      loading.value = false;

      console.log('not passing', error);
      getFormErrorMessage(error);
    }
  }
  function handleResetFields() {
    // resetFields();
    setFieldsValue(oldValue);
  }
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;
      ::v-deep(.ant-col-14){
        margin: 10px 0;
      }
      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }
    .form-box {
      width: 100%;
      height: 100%;
      // background-color: #fff;
    }
  }

  .btns {
    width: 100%;
    padding-left: 120px;
    box-sizing: border-box;

    .btns-one {
      margin-right: 10px;
    }
  }
</style>
